package com.tbr.blockchain.security;

import org.eclipse.jetty.util.security.Credential;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class CryptoUtil {
    private CryptoUtil(){

    }

    public static String SHA256(String str) {
        MessageDigest messageDigest;
        String encoder="";

        try {
            messageDigest=MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            encoder=byte2Hex(messageDigest.digest());
        } catch (Exception e) {
            System.out.println("getSHA256 is error"+ e.getMessage());
        }
        return encoder;
    }

    public static String MD5(String str){
        String resultStr= Credential.MD5.digest(str);
        return resultStr.substring(4,resultStr.length());

    }
    private static String byte2Hex(byte[] digest) {
       StringBuilder builder=new StringBuilder();
       String temp;
       for(int i=0;i<digest.length;i++){
           temp=Integer.toHexString(digest[i]&0xFF);
           if(temp.length()==1)
               builder.append("0");
           builder.append(temp);
       }
       return builder.toString();
    }
    public static String UUID(){
        return UUID.randomUUID().toString();

    }

}
